<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 总包签证确认归档编辑 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="基本信息"></title-name>
          <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''" @select="selectOrg">
            <!-- 附件上传 -->
            <template #fileInfoList>
              <template v-if="editModel != 0">
                <l-table businessCode="BM27" :uploadArrys.sync="form.fileInfoList"></l-table>
              </template>
              <file-link v-else :fileList="form.fileInfoList" style="margin-top: -3px"></file-link>
            </template>
          </custom-form>
        </a-card>
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top" v-if="editModel != 0">
          <a-button
            class="button_right"
            v-if="form.status == 'REJECTED'"
            type="primary"
            :loading="loadingBtn.REJECTED"
            @click="handleSubmit('REJECTED')"
            >保存</a-button
          >
          <span v-else>
            <a-button v-if="!visaNameDisabled"
              class="button_right"
              type="primary"
              :loading="loadingBtn.DRAFT"
              @click="handleSubmit('DRAFT')"
              >保存草稿</a-button>
          </span>
          <a-button  v-if="!visaNameDisabled"
            class="button_right"
            type="primary"
            :loading="loadingBtn.SUBMITTED"
            @click="handleSubmit('SUBMITTED')"
            >提交</a-button
          >
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
        <div class="btn_box page-btn-right-top" v-else>
          <a-button @click="handleActiveClose">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
     <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import {
  getCommercialVisaConfirmationFilingById,
  getDropDownChoice,
  addlVisaConfimlData,
  editVisaConfimlData
} from '@/api/businessAffairs/visaConfirm'
import { isIntNumber, createValidator,positiveNumberReg} from '@/utils/regExpression.js'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany
  },
  data() {
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: { projectDeptId: void 0, commissionFileInfoList: [],projectId:null}, // 表单
      visaNameDisabled: null, //是否禁用签证名称
      id: '',
      dropDownChoiceData:[], //签证名字
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {
        visaName: [{ required: true, message: '请选择' }],
        postponeDays: [
          { required: true, message: '请输入发包人认可工期顺延天数', trigger: 'blur' },
          { validator: createValidator(isIntNumber, '请输入正确发包人认可工期顺延天'), trigger: 'blur' },
        ],
        confirmAmountNo: [
          { required: true, message: '请输入确认金额(不含税)(元)', trigger: 'blur' },
          { validator: createValidator(positiveNumberReg, '数字2位小数'), trigger: 'blur' },
        ],
        confirmAmountTaxes: [
          { required: true, message: '请输入确认金额(税金)(元)', trigger: 'blur' },
          { validator: createValidator(positiveNumberReg, '数字并最多2位小数'), trigger: 'blur' },

        ],
        // fileInfoList: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }]
      }, // 校验规则
      init: false, // 初始化控件

      disabledDateList: [],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    // 监听附件实现附件校验
    // 'form.fileInfoList'() {
    //   if (this.editModel != 0 && this.init) {
    //     this.$nextTick(() => {
    //       this.$refs.ruleForm?.validateField('fileInfoList')
    //     })
    //   }
    // },
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    },
    //监听 确认金额(不含税)(元)
    'form.confirmAmountNo'(newVal) {
      let add = this.form.confirmAmountTaxes ? this.form.confirmAmountTaxes * 1 + newVal * 1 : newVal
      this.$set(this.form, 'confirmAmountHas', add)
    },
    //监听 确认金额(税金)(元)
    'form.confirmAmountTaxes'(newVal) {
      let add = this.form.confirmAmountNo ? this.form.confirmAmountNo * 1 + newVal * 1 : newVal
      this.$set(this.form, 'confirmAmountHas', add)
    },
    'form.confirmAmountHas'(newval) {
      this.profitMarginFn(newval, this.form.correspondingCostHaveVat)
    },
    //监听 对应成本(含税)(元)
    'form.correspondingCostHaveVat'(old, newval) {
      this.profitMarginFn(this.form.confirmAmountHas, newval)
    },
    //监听 签证名称
    'form.visaName'() {
      let that = this
      that.profitMarginFn(that.form.confirmAmountHas || 0, that.form.correspondingCostHaveVat || 0)
    }
  },
  created() {},
  async mounted() {
    this.$route.meta.title = ['总包签证确认归档 查看', '总包签证确认归档 编辑', '总包签证确认归档 新增'][this.editModel]
    await this.getDetailData()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('commercial_visa_confirmation_filing_audit');
  },
  computed: {
    formList() {
      return [
        {
            label: '所属单位',
            type: 'orgTree',
            keyName: 'projectId',
            rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
            span: 16,
            isAutoSelectFirst: true,
            isNeedAuth:true ,
            checkStrictly: true,
            disabled: true,
            viewName: "viewName",
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   label: '所属分公司',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   disabled: true,
        //   attrs: {
        //     isDefaultSelected: this.editModel == 2,
        //     autoSelected: this.editModel == 2,
        //     keyValue: 'branchComId',
        //     isClear: this.editModel == 2,
        //     isEdit: this.editModel != 2,
        //     form: this.form
        //   }
        // },
        {
          keyName: 'visaName',
          type: BSelect,
          disabled: this.editModel == 0 || this.visaNameDisabled,
          label: '签证名称',
          attrs: {
            form: this.form,
            keyValue: 'projectId',
            request: this.getNameList
          },
          selectChange: (e) => {
            //切换签证名称获取数据
            this.form.typleName = e.typleName
            this.form.typleId = e.typleId
            this.form.visaCode = e.visaId
            this.form.visaId = e.id
            this.form.contractValuationBasis = e.contractValuationBasis
            this.form.saveFileDept = e.saveFileDept
            this.form.submitTime = e.submitTime
            this.form.contractAppointSubmitTime = e.contractAppointSubmitTime
            this.form.changeDays = e.daysInvolvedInConstructionPeriodChange
            this.form.chargePersonName = e.chargeNames
            this.form.chargePersonId = e.commercialVisaSendApproveChargePeople.chargePersonId
            this.form.submitMoneyHaveVat = e.addedTaxFeeSend || 0
            this.form.correspondingCostHaveVat = e.addedTaxFeeBase || 0
          }
        },
        {
          keyName: 'typleName',
          type: 'a-select',
          disabled: true,
          label: '类型',
          placeholder: '自动带出',
        },
        {
          keyName: 'visaCode',
          type: 'BaseInput',
          disabled: true,
          label: '签证编号'
        },
        {
          keyName: 'contractValuationBasis',
          type: 'BaseInput',
          disabled: true,
          label: '合同计价依据'
        },
        {
          keyName: 'saveFileDept',
          type: 'BaseInput',
          disabled: true,
          label: '存档部门'
        },
        {
          keyName: 'submitTime',
          type: 'BaseInput',
          disabled: true,
          label: '报送时间'
        },
        {
          keyName: 'contractAppointSubmitTime',
          type: 'BaseInput',
          disabled: true,
          label: '合同约定应报送时间'
        },
        {
          keyName: 'changeDays',
          type: 'BaseInput',
          disabled: true,
          label: '涉及工期变更天数'
        },
        {
          keyName: 'postponeDays',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          label: '发包人认可工期顺延天数'
        },
        {
          keyName: 'chargePersonName',
          type: 'BaseInput',
          disabled: true,
          label: '责任人'
        },
        {
          keyName: 'submitMoneyHaveVat',
          type: 'BaseInput',
          disabled: true,
          label: '报送金额(含税)(元)'
        },
        {
          keyName: 'correspondingCostHaveVat',
          type: 'BaseInput',
          disabled: true,
          label: '对应成本(含税)(元)'
        },
        {
          keyName: 'confirmAmountNo',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          label: '确认金额(不含税)(元)',
          precision: 2,
        },
        {
          keyName: 'confirmAmountTaxes',
          type: 'BaseInputNumber',
          label: '确认金额(税金)(元)',
          disabled: this.editModel == 0,
          precision: 2,
        },
        {
          keyName: 'confirmAmountHas',
          type: 'BaseInput',
          disabled: true,
          label: '确认金额(含税)(元)'
        },
        {
          keyName: 'profitRate',
          type: 'BaseInput',
          disabled: true,
          label: '利润率%'
        },
        {
          slot: true,
          keyName: 'fileInfoList',
          label: '附件上传',
          span: 24,
          businessCode: 'FACE09'
        }
      ]
    }
  },
  methods: {
    //选择单位
    selectOrg(val) {
        if (val && val.length) {
            this.form.branchComId = val[val.length - 2].orgId
        }
    },
    //获取项目详情
    getProjectInfo(e) {
        this.$set(this.form, 'projectDeptId', e.projectDeptId)
    },
    //计算利润率
    profitMarginFn(a = 0, b = 0) {
      let profitMargin = 0
      if (a && b) {
        profitMargin = (((a * 1 - b * 1) / a) * 1 * 100)?.toFixed(2) || 0
      }
      this.$set(this.form, 'profitRate', profitMargin)
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
      return flag
    },
    async getNameList() {
      let param = {
        projectId: this.form.projectId || null,
        id:this.form.id || 0
      }
      if (this.editModel * 1 !== 0 && param.projectId) {
        return getDropDownChoice(param)
          .then((res) => {
            if (res.code == 0) {
              res.data.map((item) => {
                item.name = item.visaName
              })
              this.visaNameDisabled = res.data.length ? false : true //有数据才能选中
              if(this.editModel * 1===2 && !res.data.length){     //新增时和签证名称数据不存在，提示不能新增
                  this.$message.warning('签证名称无数据,不能新增');
              }
              this.dropDownChoiceData = res.data ||[];
              return { code: 200, data: res.data }
            }
            return { code: 200, data: [] }
          })
          .catch(() => {
            return { code: 200, data: [] }
          })
      } else {
        return ''
      }
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        getCommercialVisaConfirmationFilingById({ id: this.id })
          .then((res) => {
            this.loading = false
            this.form = { ...this.form, ...res.data }
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.form.projectId = this.$userInfo().currentPost.projectId;
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
    /**
     * 提交表单
     */
    handleSubmit(status) {
      this.setProcessConfig = null;
      if (status == 'SUBMITTED' && !this.validateForm()) {
        return
      }
      this.loading = true
      this.loadingBtn[status] = true
      let findData = this.dropDownChoiceData.find((item)=>{
         return item.id === this.form.visaId;
       })
       this.form.visaName = findData?findData.visaName: this.form.visaName ;
      let form = this.$clone(this.form);

      if (status != 'REJECTED') {
        form.auditStatus = status == 'SUBMITTED' ? 1 : 0
      } else {
        form.auditStatus = 5
      }
      let api = [editVisaConfimlData, addlVisaConfimlData][this.editModel - 1]
      this.submitApprovalConfirm(status == 'SUBMITTED'?this.processConfig:6, (flag)=>{
        if(!flag) {
          this.loading = false
          this.loadingBtn[status] = false
          return
        }
      api(form)
        .then((res) => {
          this.loading = false
          this.loadingBtn[status] = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          //提交时，返回id
          if(status =='SUBMITTED') {
            //提交时，返回id
                this.businessId = res.data?.id || this.id;
                this.setProcessConfig = this.processConfig;
                return
            }else{
             this.$multiTab.close()
          }
        })
        .catch(() => {
          this.loadingBtn[status] = false
          this.loading = false
          this.$message.warning(err.data.message)
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
.item {
  margin-left: 60px;
  margin-bottom: 0;
}
.item .ant-form-item {
  margin-top: -28px;
}
</style>
